﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

using System.IO;
using System.IO.IsolatedStorage;
using Microsoft.Phone.BackgroundAudio;
using Microsoft.Xna.Framework.Audio;
using System.ComponentModel;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;

namespace XiaMiRingtone
{
    public partial class editring : PhoneApplicationPage
    {
        string filename;
        IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();

        public editring()
        {
            InitializeComponent();
            StartTimer();
            SetSkin();
        }

        private void SetSkin()
        {
            var store = IsolatedStorageFile.GetUserStoreForApplication();
            if (store.FileExists("skin.jpg"))
            {
                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("skin.jpg", FileMode.Open, store))
                {
                    BitmapImage bi = new BitmapImage();
                    bi.SetSource(stream);
                    Ib.ImageSource = bi;
                }
            }
        }

        public void StartTimer()
        {
            System.Windows.Threading.DispatcherTimer myDispatcherTimer = new System.Windows.Threading.DispatcherTimer();
            myDispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100);
            myDispatcherTimer.Tick += new EventHandler(Each_Tick);
            myDispatcherTimer.Start();// A variable to count with.

        }
        public void Each_Tick(object o, EventArgs sender)
        {
            SetUi();
            if ((int)(slider1.Maximum - slider2.Value - slider1.Value) >= 40 || (int)(slider1.Maximum - slider2.Value - slider1.Value) <= 0)
            {
                button2.IsEnabled = false;
                button1.IsEnabled = false;
            }
            else
            {
                button2.IsEnabled = true;
                button1.IsEnabled = true;
            }

            if (mediaElement1.Position.TotalSeconds > (slider2.Maximum - slider2.Value))
            {
                mediaElement1.Pause();
            }
        }
        //当该页面是活动页面时触发
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);//调用基类的虚方法是应该的，但不是必须的

            if (NavigationContext.QueryString.ContainsKey("name"))
            {
                filename = NavigationContext.QueryString["name"];
                PageTitle.Text = filename;
                ISetSource();
            }
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);//调用基类的虚方法是应该的，但不是必须的
            mediaElement1.Stop();
        }

        void SetUi()
        {
            slider1.Maximum = mediaElement1.NaturalDuration.TimeSpan.TotalSeconds;
            slider2.Maximum = mediaElement1.NaturalDuration.TimeSpan.TotalSeconds;
        }

        private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            textBlock1.Text = "开始时间： "+TimeConvert(e.NewValue);

            textBlock3.Text = "铃声长度： "+((int)(slider1.Maximum - slider2.Value - slider1.Value)).ToString();

        }

        private void slider2_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            textBlock2.Text = "结束时间： "+TimeConvert(slider2.Maximum -e.NewValue);
            textBlock3.Text = "铃声长度： "+((int)(slider1.Maximum - slider2.Value - slider1.Value)).ToString();
        }

        public string TimeConvert(double a)
        {
            int f = (int)a / 60;
            int m = (int)a % 60;
            return f.ToString() +" : "+ m.ToString();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            mediaElement1.Position = new TimeSpan(0, 0, (int)(slider1.Value));
            mediaElement1.Volume = 1;
            mediaElement1.Play();
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            SaveRing();
            SetRing();
        }

        void SaveRing()
        {

            IsolatedStorageFileStream oldstream = new IsolatedStorageFileStream("temp\\temp.mp3", FileMode.Open, store);

            if (store.FileExists("temp\\temp2.mp3"))
            {
                store.DeleteFile("temp\\temp2.mp3");
            }
            IsolatedStorageFileStream tempstream = new IsolatedStorageFileStream("temp\\temp2.mp3", FileMode.Create, store);

            if (store.FileExists("rings" + filename))
            {
                store.DeleteFile("rings" + filename);
            }
            IsolatedStorageFileStream newstream = new IsolatedStorageFileStream("rings\\" + filename, FileMode.Create, store);

            oldstream.Position = (long)(GetPositon()*(oldstream.Length) );
            oldstream.CopyTo(tempstream);
            tempstream.Close();
            

            IsolatedStorageFileStream temp = new IsolatedStorageFileStream("temp\\temp2.mp3", FileMode.Open, store);
            BinaryWriter newwriter = new BinaryWriter(newstream);
            BinaryReader tempreader = new BinaryReader(temp);

            int filesize = (int)(GetFileSize() * (oldstream.Length));
            byte[] TempBytes = new byte[filesize];
            
            TempBytes = tempreader.ReadBytes(filesize);
            newwriter.Write(TempBytes);

            oldstream.Close();
            newwriter.Close();
            newstream.Close();
            tempreader.Close();
            temp.Close();
        }

        void ISetSource()
        {
            IsolatedStorageFileStream filestream = store.OpenFile(filename, FileMode.Open, FileAccess.Read);
            CreatDir();
            if (store.FileExists("temp\\temp.mp3"))
            {
                store.DeleteFile("temp\\temp.mp3");
            }
            IsolatedStorageFileStream tempstream = store.OpenFile("temp\\temp.mp3", FileMode.Create, FileAccess.Write);
            filestream.CopyTo(tempstream);
            
            mediaElement1.SetSource(filestream);
            mediaElement1.Pause();
            filestream.Close();
            tempstream.Close();
        }

        void CreatDir()
        {
            if (store.DirectoryExists("temp") == false)
            {
                store.CreateDirectory("temp");
            }
            if (store.DirectoryExists("rings") == false)
            {
                store.CreateDirectory("rings");
            }
        }

        double GetPositon()
        {
            double  a = (slider1.Value) / (slider1.Maximum);
            return a;
        }

        double GetFileSize()
        {
            double a = (slider1.Maximum - slider2.Value - slider1.Value) / (slider1.Maximum);
            return a;
        }

        void SetRing()
        {
            SaveRingtoneTask saveRingtoneChooser = new SaveRingtoneTask();
            saveRingtoneChooser.Completed += new EventHandler<TaskEventArgs>(saveRingtoneChooser_Completed);

            try
            {
                saveRingtoneChooser.Source = new Uri("isostore:/rings//"+filename); 

                saveRingtoneChooser.DisplayName = filename;

                saveRingtoneChooser.Show();
            }
            catch (System.InvalidOperationException e)
            {
                MessageBox.Show(e.Message);
            }
        }

        void saveRingtoneChooser_Completed(object sender, TaskEventArgs e)
        {
            switch (e.TaskResult)
            {
                //Logic for when the ringtone was saved successfully
                case TaskResult.OK:
                    MessageBox.Show("铃声保存成功！");
                    break;

                //Logic for when the task was cancelled by the user
                case TaskResult.Cancel:
                    MessageBox.Show("铃声无法保存！");
                    break;

                //Logic for when the ringtone could not be saved
                case TaskResult.None:
                    MessageBox.Show("铃声无法保存！");
                    break;
            }
        }
    }
}